import machine, neopixel
import time
from lib.config.index import sensor_config


"""
WS2812 WS2812B 灯带
"""

np = None


def init_ws2812():
    global np
    ws2812_config = sensor_config.get_sensor("ws2812")
    if not ws2812_config:
        return
    print(ws2812_config)
    pin_num = ws2812_config["pin"]
    num = ws2812_config["num"]
    np = neopixel.NeoPixel(machine.Pin(pin_num), int(num))


def clear():
    global np
    n = np.n
    for i in range(n):
        np[i] = (0, 0, 0)
    np.write()


def cycle():
    global np
    n = np.n
    for i in range(4 * n):
        for j in range(n):
            np[j] = (0, 0, 0)
        np[i % n] = (255, 255, 255)
        np.write()
        time.sleep_ms(25)


def bounce():
    global np
    n = np.n
    for i in range(4 * n):
        for j in range(n):
            np[j] = (0, 0, 128)
        if (i // n) % 2 == 0:
            np[i % n] = (0, 0, 0)
        else:
            np[n - 1 - (i % n)] = (0, 0, 0)
        np.write()
        time.sleep_ms(60)


def fadeInOut(count=1):
    global np
    n = np.n
    for i in range(0, count * 2 * 256, 8):
        for j in range(n):
            if (i // 256) % 2 == 0:
                val = i & 0xFF
            else:
                val = 255 - (i & 0xFF)
            np[j] = (val, val, val)
        np.write()


def show_np_demo():
    # cycle
    cycle()
    # bounce
    bounce()
    # fade in/out
    fadeInOut()
    # clear
    clear()


def show_rainbow():
    global np
    n = np.n


if __name__ == "__main__":
    init_ws2812()
    fadeInOut()
